﻿using CommandProcessor.Dispatcher;
using Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using AutoMapper;
using QuanLySanXuat.Models;
using Domain.Commands;
using Core.Common;
using Core.Extensions;
using Data.Models;
namespace QuanLySanXuat.Controllers
{
    public class BOMController : Controller
    {
        private readonly ICommandBus commandBus;
        private readonly IBOMRepository BOMRepository;
        private readonly IBOMDetailRepository BOMDetailRepository;
        private readonly IBOMAccessorie_DetailsRepository BOMAccesRepository;
        private readonly IProductRepository productRepository;
        private readonly IMaterialRepository materialRepository;
        private readonly IAccessoryRepository accessrorylRepository;
        private readonly IWorkerLevelRepository workerRepository;
        private readonly IMachineRepository machineRepository;
        private readonly IUOMRepository uomRepository;
        public BOMController(ICommandBus commandBus, IBOMRepository BOMRepository, IProductRepository productRepository, IMaterialRepository materialRepository, IBOMDetailRepository BOMDetailRepository, IUOMRepository uomRepository, IAccessoryRepository accessrorylRepository, IWorkerLevelRepository workerRepository, IMachineRepository machineRepository, IBOMAccessorie_DetailsRepository BOMAccesRepository)
        {
            this.commandBus = commandBus;
            this.BOMRepository = BOMRepository;
            this.productRepository = productRepository;
            this.materialRepository = materialRepository;
            this.BOMDetailRepository = BOMDetailRepository;
            this.uomRepository = uomRepository;
            this.accessrorylRepository = accessrorylRepository;
            this.workerRepository = workerRepository;
            this.machineRepository = machineRepository;
            this.BOMAccesRepository = BOMAccesRepository;
        }
        //
        // GET: /BOM/
        [HttpGet]
        public ActionResult Index()
        {
            var prodcutType = BOMRepository.GetAll();
            return View(prodcutType.ToPagedList(1, 10));
        }
        [HttpGet]
        public ActionResult Create(int? ID)
        {
            //ViewData["Product"] = new SelectList(productRepository.GetAll().ToList(), "ID","Name");
            ViewData["Product"] = productRepository.GetAll();
            ViewData["Material"] = materialRepository.GetAll();
            ViewData["BOM"] = BOMRepository.GetAll();
            ViewData["UOM"] = uomRepository.GetAll();
            ViewData["Accessory"] = accessrorylRepository.GetAll();
            ViewData["Worker"] = workerRepository.GetAll();
            ViewData["Machine"] = machineRepository.GetAll();
            BOM bom = BOMRepository.GetById(ID??0);
            var bomModels = Mapper.Map<BOM, BOMFormModels>(bom);
            if (bom != null)
            {
                var bomDetail = BOMDetailRepository.GetMany(x => x.BOMID == bom.ID);
                var AccesDetail=BOMAccesRepository.GetMany(x => x.BOMID == bom.ID);

                bomModels.BOMDetailFormModels = bomDetail;
                bomModels.BOMAccessorie_DetailsFormModels = AccesDetail;
            }
           
            return View(bomModels);
        }
        [HttpPost]
        public ActionResult Save(BOMFormModels frm)
        {
            var form = new BOMFormModels()
            {
                ID = frm.ID,
                Active=frm.Active,
                EffectiveDate=DateTime.Now,
                ProductID =frm.ProductID,
                Description = frm.Description,
                Name = frm.Name,
                Code=frm.Code,
                Color=frm.Color
            };
            var command = Mapper.Map<BOMFormModels, CreateOrUpdateBOMCommand>(form);
            IEnumerable<ValidationResult> errors = commandBus.Validate(command);
            ModelState.AddModelErrors(errors);
                //Insert or update BOM
                var result = commandBus.Submit(command);

                //EMty BOMDetail
                List<CreateOrUpdateBOMDetailCommand> list = new List<CreateOrUpdateBOMDetailCommand>();
                var deletes = BOMDetailRepository.GetMany(x => x.BOMID == result.ID);
                foreach (var e in deletes)
                {
                    var BOMDetail = new BOMDetailFormModels{ ID = Convert.ToInt16(e.ID) };
                    var com = Mapper.Map<BOMDetailFormModels, CreateOrUpdateBOMDetailCommand>(BOMDetail);
                    list.Add(com);
                }
                commandBus.DeleteRange(list);

                //Insert BOMDetail
                if (frm.MaterialID != null)
                {
                    var commandBOMDetails = new List<CreateOrUpdateBOMDetailCommand>();
                    for (int i = 0; i < frm.MaterialID.Length; i++)
                    {
                        int parentID = 0;
                        if (frm.ParentBOMID != null)
                        {
                            parentID = frm.ParentBOMID[i];
                        }
                        var BOMDetail = new BOMDetailFormModels()
                        {
                            BOMID = result.ID,
                            MaterialID = frm.MaterialID[i],
                            Description = frm.Detail[i],
                            Quantity = frm.Quantity[i],
                            ParentBOMID = parentID,
                            UnitID = frm.UnitID[i]
                        };
                        var commandBD = Mapper.Map<BOMDetailFormModels, CreateOrUpdateBOMDetailCommand>(BOMDetail);
                        commandBOMDetails.Add(commandBD);
                    }
                    commandBus.SubmitRange(commandBOMDetails);
                }
            //Insert bảng phụ kiện
                //Emty bảng phụ kiện chi tiết
                List<CreateOrUpdateBOMAccessorie_DetailsCommand> lst = new List<CreateOrUpdateBOMAccessorie_DetailsCommand>();
                var deletesAcess = BOMAccesRepository.GetMany(x => x.BOMID == result.ID);
                foreach (var e in deletesAcess)
                {
                    var BOMDetail = new BOMAccessorie_DetailsFormModels { ID = Convert.ToInt16(e.ID) };
                    var com = Mapper.Map<BOMAccessorie_DetailsFormModels, CreateOrUpdateBOMAccessorie_DetailsCommand>(BOMDetail);
                    lst.Add(com);
                }
                commandBus.DeleteRange(lst);
                //Them du lieu vao bang phu kien chi tiet
                if (frm.AccessorieID != null)
                {
                    var commandBOMAcessDetails = new List<CreateOrUpdateBOMAccessorie_DetailsCommand>();
                    for (int i = 0; i < frm.AccessorieID.Length; i++)
                    {
                        var BOMDetail = new BOMAccessorie_DetailsFormModels()
                        {
                            BOMID = result.ID,
                            AccessorieID = frm.AccessorieID[i],
                            Description = frm.DetailAcces[i],
                            Quantity = frm.QuantityAcces[i],
                            UnitID = frm.UnitIDAcces[i],
                            Price=frm.PriceAcces[i]
                        };
                        var commandBD = Mapper.Map<BOMAccessorie_DetailsFormModels, CreateOrUpdateBOMAccessorie_DetailsCommand>(BOMDetail);
                        commandBOMAcessDetails.Add(commandBD);
                    }
                    commandBus.SubmitRange(commandBOMAcessDetails);
                }

            ////Emty bang nhan cong
            //    List<CreateOrUpdateBOMWorker_DetailsCommand> lst = new List<CreateOrUpdateBOMWorker_DetailsCommand>();
            //    var deletesAcess = BOMAccesRepository.GetMany(x => x.BOMID == result.ID);
            //    foreach (var e in deletesAcess)
            //    {
            //        var BOMDetail = new BOMAccessorie_DetailsFormModels { ID = Convert.ToInt16(e.ID) };
            //        var com = Mapper.Map<BOMAccessorie_DetailsFormModels, CreateOrUpdateBOMAccessorie_DetailsCommand>(BOMDetail);
            //        lst.Add(com);
            //    }
            //    commandBus.DeleteRange(lst);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public JsonResult GetMaterial(int ID)
        {
            Material material = materialRepository.GetById(ID);
            var obj = Mapper.Map<Material, MaterialFormModels>(material);
            return Json(obj, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public JsonResult GetAcces(int ID)
        {
            Accessory material = accessrorylRepository.GetById(ID);
            var obj = Mapper.Map<Accessory, AccessoryFormModels>(material);
            return Json(obj, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult RemoveItems(string[] ProID)
        {
            List<DeleteBOMCommand> list = new List<DeleteBOMCommand>();
            foreach (var item in ProID)
            {
                var command = new DeleteBOMCommand { ID = Convert.ToInt16(item) };
                list.Add(command);
            }
            //Xoa bang bom
            var result = commandBus.SubmitRange(list);


            var model = BOMRepository.GetAll();
            return PartialView("_BOMList", model.ToPagedList(1, 10));
        }
        [HttpGet]
        public ActionResult Search(string Name)
        {
            IEnumerable<BOM> model;
            if (String.IsNullOrEmpty(Name))
            {
                model = BOMRepository.GetAll();
            }
            else
            {
                model = BOMRepository.GetMany(x => (x.Name.Contains(Name)) || (x.Description.Contains(Name)));

            }
            return PartialView("_BOMList", model.ToPagedList(1, 10));
        }
        [HttpGet]
        [ValidateInput(false)]
        public ActionResult Page(int PageID)
        {
            var prodcutType = BOMRepository.GetAll();
            return PartialView("_BOMList", prodcutType.ToPagedList(1, PageID));
        }
    }
}
